<template>
  <div class="content-wrap">
    <Row class="card-title" type="flex" justify="space-between">
      <span class="title">维护图文信息</span>
      <Col>
        <el-button
          v-preventReClick
          type="text"
          size="large"
          :loading="saveBtnLoading"
          @click="handleSubmit(false)"
          >保存</el-button
        >
        <el-button
          v-show="showBtn('提交')"
          v-preventReClick
          type="text"
          size="large"
          :loading="saveBtnLoading"
          @click="handleSubmit(true)"
          >提交</el-button
        >
      </Col>
    </Row>
    <div class="content">
      <Card dis-hover>
        <p slot="title">SPU 图片</p>
        <p slot="extra">
          <span class="mr-10"><b>SPU编码：</b>{{ spuNo }}</span>
          <span><b>商品名称：</b>{{ productName }}</span>
        </p>
        <Form :label-width="180">
          <FormItem label="商品主图片（未精修）">
            <Row>
              <RadioGroup v-model="button1" type="button">
                <Radio label="本地上传"></Radio>
                <Radio label="图片库上传"></Radio>
              </RadioGroup>
            </Row>
            <Row
              style="padding-top: 10px"
              v-show="button1 == '本地上传'"
            >
              <Upload
                class="ivu-mr qw-disflex"
                :defaultList="goodsAvaterUntruing"
                :maxSize="2048"
                :maxLen="1"
                :format="['jpg', 'jpeg', 'png']"
                @handleChangeImage="changeImageKey1"
              ></Upload>
            </Row>
            <Row
              style="padding-top: 10px"
              v-show="button1 == '图片库上传'"
            >
              <photo
                :maxlength="1"
                :defaultList="goodsAvaterUntruing"
                @child-imglist="getChildPhoto($event, '1')"
              ></photo>
            </Row>
          </FormItem>
          <FormItem label="商品主图片（精修）" :required="true">
            <Row>
              <RadioGroup v-model="button2" type="button">
                <Radio label="本地上传"></Radio>
                <Radio label="图片库上传"></Radio>
              </RadioGroup>
            </Row>
            <Row
              style="padding-top: 10px"
              v-show="button2 == '本地上传'"
            >
              <Upload
                class="ivu-mr qw-disflex"
                :defaultList="goodsAvaterTruing"
                :maxSize="2048"
                :maxLen="1"
                :format="['jpg', 'jpeg', 'png']"
                @handleChangeImage="changeImageKey2"
              ></Upload>
            </Row>
            <Row
              style="padding-top: 10px"
              v-show="button2 == '图片库上传'"
            >
              <photo
                :maxlength="1"
                :defaultList="goodsAvaterTruing"
                @child-imglist="getChildPhoto($event, '2')"
              ></photo>
            </Row>
          </FormItem>
          <FormItem label="商品多角度图（未精修）">
            <Row>
              <RadioGroup v-model="button3" type="button">
                <Radio label="本地上传"></Radio>
                <Radio label="图片库上传"></Radio>
              </RadioGroup>
            </Row>
            <Row
              style="padding-top: 10px"
              v-show="button3 == '本地上传'"
            >
              <Upload
                class="ivu-mr qw-disflex"
                :isMultiple="true"
                :defaultList="goodsMultiangleUntruing"
                :maxSize="2048"
                :maxLen="5"
                :format="['jpg', 'jpeg', 'png']"
                @handleChangeImage="changeImageKey3"
              ></Upload>
            </Row>
            <Row
              style="padding-top: 10px"
              v-show="button3 == '图片库上传'"
            >
              <photo
                :maxlength="5"
                :defaultList="goodsMultiangleUntruing"
                @child-imglist="getChildPhoto($event, '3')"
              ></photo>
            </Row>
            <div class="note">提示：可以添加5张</div>
          </FormItem>
          <FormItem label="商品多角度图（精修）" :required="true">
            <Row>
              <RadioGroup v-model="button4" type="button">
                <Radio label="本地上传"></Radio>
                <Radio label="图片库上传"></Radio>
              </RadioGroup>
            </Row>
            <Row
              style="padding-top: 10px"
              v-show="button4 == '本地上传'"
            >
              <Upload
                class="ivu-mr qw-disflex"
                :isMultiple="true"
                :defaultList="goodsMultiangleTruing"
                :maxSize="2048"
                :maxLen="5"
                :format="['jpg', 'jpeg', 'png']"
                @handleChangeImage="changeImageKey4"
              ></Upload>
            </Row>
            <Row
              style="padding-top: 10px"
              v-show="button4 == '图片库上传'"
            >
              <photo
                :maxlength="5"
                :defaultList="goodsMultiangleTruing"
                @child-imglist="getChildPhoto($event, '4')"
              ></photo>
            </Row>
            <div class="note">提示：可以添加5张</div>
          </FormItem>
        </Form>
      </Card>
      <Card style="margin-top: 16px" dis-hover title="SKU 图片">
        <Table
          style="margin-bottom: 16px"
          border
          ref="selection"
          @on-select="handleSelect"
          @on-select-cancel="handleSelectCancel"
          @on-select-all="handleSelectAll"
          @on-select-all-cancel="handleSelectAllCancel"
          :columns="columns4"
          :data="skuList"
        ></Table>
        <Form>
          <FormItem
            class="item-wrap"
            v-for="(item, index) in tableSelect"
            :key="index"
          >
            <div class="sku-info">
              <div><b>SKU编码：</b>{{ item.skuNo }}</div>
              <div><b>SKU名称：</b>{{ item.skuName }}</div>
              <div><b>SKU规格：</b>{{ item.specDetailStr }}</div>
            </div>
            <div class="sku-img">
              <Row>
                <RadioGroup v-model="item.button" type="button">
                  <Radio label="本地上传"></Radio>
                  <Radio label="图片库上传"></Radio>
                </RadioGroup>
              </Row>
              <Row
                style="padding-top: 10px"
                v-show="item.button == '本地上传'"
              >
                <Upload
                  class="ivu-mr qw-disflex"
                  :isMultiple="true"
                  :defaultList="item.img"
                  :maxSize="2048"
                  :maxLen="3"
                  :format="['jpg', 'jpeg', 'png']"
                  @handleChangeImage="changeSkuImageKey($event, index)"
                >
                </Upload>
              </Row>
              <Row
                style="padding-top: 10px"
                v-show="item.button == '图片库上传'"
              >
                <photo
                  :maxlength="3"
                  :defaultList="item.img"
                  @child-imglist="getChildPhoto($event, 's', index)"
                ></photo>
              </Row>
              <div class="note">提示：可以添加3张</div>
            </div>
          </FormItem>
        </Form>
      </Card>
      <Card style="margin-top: 16px; height: 1000px" dis-hover>
        <!-- <RadioGroup v-model="animal">
        <Radio label="1">移动端/PC使用同一详情</Radio>
        <Radio label="2">移动端/PC不使用同一详情</Radio>
      </RadioGroup> -->
        <Form style="padding-top: 16px">
          <FormItem label="详情信息" :required="true">
            <div style="display: block; padding-top: 20px">
              <i-quill
                v-model="pcDetail"
                @on-change="handleInputChange('pc')"
              ></i-quill>
            </div>
          </FormItem>
          <FormItem v-if="animal == '2'" label="移动端详情">
            <div style="display: block; padding-top: 20px">
              <i-quill
                v-model="phoneDetail"
                @on-change="handleInputChange('')"
              ></i-quill>
            </div>
          </FormItem>
        </Form>
      </Card>
    </div>
    <el-backtop target="#app .i-layout-content-main">
      <i class="el-icon-top"></i>
    </el-backtop>
  </div>
</template>

<script>
import { ApiRequest } from '@api/basePage';
import iQuill from '@/components/quill'; // 编辑器组件
import Upload from '@/components/common/upload'; // 上传组件
// import photo from './component/photoGallery'; // 图片库选择
import photo from '@/components/common/photoGallery'; // 图片库选择
// import { uniqueImageKeyData } from '@/assets/js/utils';
import { mapGetters } from 'vuex';

export default {
  name: 'tuwenjieshao',
  components: {
    iQuill,
    Upload,
    photo,
  },
  data () {
    return {
      saveBtnLoading: false,
      productUuid: '', // 商品uuid
      productName: '', // 商品名称
      spuNo: '', // 商品spu编码
      animal: '1',
      brandImageKey2: [],
      vediolist: [],
      button1: '本地上传',
      button2: '本地上传',
      button3: '本地上传',
      button4: '本地上传',
      tableSelect: [],
      goodsAvaterTruing: [], // 商品主图片-精修
      goodsAvaterUntruing: [], // 商品主图片-未精修
      goodsMultiangleTruing: [], // 商品多角度-精修
      goodsMultiangleUntruing: [], // 商品多角度-未精修
      skuImageList: [], // sku图片
      phoneDetail: '', // 移动端详情
      pcDetail: '', // PC端详情
      isNew: '1', // 1 新增  2 修改
      recordNo: '', // 单据号
      columns4: [
        {
          type: 'selection',
          width: 60,
          align: 'center'
        },
        {
          title: 'SKU编码',
          key: 'skuNo',
          align: 'center',
          minWidth: 150
        },
        {
          title: 'SKU名称',
          key: 'skuName',
          align: 'center',
          minWidth: 150
        },
        {
          title: '规格',
          key: 'specDetailStr',
          align: 'center',
          minWidth: 150
        }
      ],
      skuList: [],
      skuList11: []
    };
  },
  computed: {
    ...mapGetters('permissions/systemBtns', ['showBtn']),
  },
  mounted () {},
  created () {
    const { productUuid, spuNo, productName } = this.$route.query;
    this.productUuid = productUuid;
    this.spuNo = spuNo;
    this.productName = productName;
    this.getSku();
  },
  methods: {
    initView () {
      var that = this;
      // 初始回显接口
      let data = {
        productUuid: that.productUuid
      };
      ApiRequest(
        '/sysback/productinfoupdate/getPicInfoByProductUuid',
        'get',
        data,
        true
      ).then((res) => {
        if (res.retStatus === '1') {
          let resData = res.retData;
          if (resData.mainImage !== null) {
            this.isNew = '2';
          }
          // 主图 未精修
          if (resData.mainImageUpdate !== null) {
            // 用于判断是否为编辑
            if (resData.mainImageUpdate.mainImageKey) {
              let mainimg = {
                url: resData.mainImageUpdate.mainImageKey,
                uid: resData.mainImageUpdate.uuid,
              };
              that.goodsAvaterUntruing.push(mainimg);
            }

            // 主图 精修
            if (resData.mainImageUpdate.trimmingKey) {
              let truingimg = {
                url: resData.mainImageUpdate.trimmingKey,
                uid: resData.mainImageUpdate.uuid,
              };
              that.goodsAvaterTruing.push(truingimg);
            }
          }
          if (resData.multiImageUpdateList !== null) {
            // 多角度图
            // let imageList = uniqueImageKeyData(resData.multiImageUpdateList);
            resData.multiImageUpdateList.forEach(function (item, index) {
              if (item.trimming === '1') {
                let imgobj = {
                  url: item.basicImageKey,
                  uid: item.uuid
                };
                that.goodsMultiangleTruing.push(imgobj);
              } else {
                let imgobj = {
                  url: item.basicImageKey,
                  uid: item.uuid
                };
                that.goodsMultiangleUntruing.push(imgobj);
              }
            });
          }

          if (resData.descriptionUpdate !== null) {
            // 图文描述
            that.animal = resData.descriptionUpdate.currency;
            that.pcDetail = resData.descriptionUpdate.description;
            that.phoneDetail = resData.descriptionUpdate.appdescrition;
          }

          // sku图片
          that.skuList11.forEach(function (skuitem, skuindex) {
            let select = {
              skuNo: skuitem.skuNo,
              img: [],
              button: '本地上传'
            };
            if (resData.skuImageUpdateList !== null) {
              // let imageList = uniqueImageKeyData(resData.skuImageUpdateList);
              resData.skuImageUpdateList.forEach(function (item, index) {
                if (skuitem.skuNo === item.skuNo) {
                  skuitem._checked = true;
                  select.skuNo = skuitem.skuNo;
                  select.skuName = skuitem.skuName;
                  select.specDetailStr = skuitem.specDetailStr;
                  select.img.push({
                    url: item.basicImageKey,
                    uid: item.uuid
                  });
                }
              });
            } else {
              skuitem._checked = true;
            }
            if (select.img.length > 0) {
              that.tableSelect.push(select);
              skuitem.img = select.img;
            }
          });
          that.skuList = that.skuList11;
        }
      });
    },
    // 商品头图片（未精修）
    changeImageKey1 (e) {
      this.goodsAvaterUntruing = e;
    },
    // 商品头图片（精修）
    changeImageKey2 (e) {
      this.goodsAvaterTruing = e;
    },
    // 商品多角度图（未精修）
    changeImageKey3 (e) {
      this.goodsMultiangleUntruing = e;
    },
    // 商品多角度图（精修）
    changeImageKey4 (e) {
      this.goodsMultiangleTruing = e;
    },
    // sku商品 图
    changeSkuImageKey (e, index) {
      this.tableSelect[index].img = e;
    },

    // 获取sku列表
    getSku () {
      let data = {};
      /// sysback/skuaudit/list/getAuditSkuByProduct
      ApiRequest(
        '/sysback/skuaudit/list/getAuditSkuByProduct?productUuid=' +
          this.productUuid,
        'post',
        data
      ).then((res) => {
        if (res.retStatus == '1') {
          let sku = res.retData;
          sku.forEach(function (item, index) {
            let button = '本地上传';
            let img = [];
            item.button = button;
            item.img = img;
          });
          this.skuList11 = sku;
          this.initView();
        }
      });
    },

    // 图片库 点击 确认 返回的图片列表
    getChildPhoto (data, i, si) {
      switch (i) {
        case '1':
          // 商品头未精修
          this.goodsAvaterUntruing = data;
          break;
        case '2':
          // 商品头精修
          this.goodsAvaterTruing = data;
          break;
        case '3':
          // 商品多角度未精修
          this.goodsMultiangleUntruing = data;
          break;
        case '4':
          // 商品多角度精修
          this.goodsMultiangleTruing = data;
          break;
        case 's':
          this.tableSelect[si].img = data;
      }
    },
    handleSelect (selection, row) {
      this.tableSelect.push(row)
    },
    handleSelectCancel (selection, row) {
      const index = this.tableSelect.findIndex(
        item => item.skuNo === row.skuNo
      );
      this.tableSelect.splice(index, 1);
    },
    handleSelectAll (selection) {
      selection.forEach(item => {
        if (this.tableSelect.findIndex(i => i.skuNo === item.skuNo) < 0) {
          this.tableSelect.push(item);
        }
      });
    },
    handleSelectAllCancel (selection) {
      this.tableSelect = selection;
    },
    handleInputChange (t) {
      if (t == 'pc') {
      } else {
      }
    },

    // 提交
    submitImageTxt () {
      // 根据是否有单据号改变接口
      let apiurl = '';
      let data = '';
      if (this.isNew == '1') {
        apiurl = '/sysback/productinfoupdate/toCreatAudit';
        data = '?productUuid=' + this.productUuid;
      } else {
        apiurl = '/sysback/productinfoupdate/toUpdateAudit';
        data = '?recordNo=' + this.recordNo;
      }
      const msg = this.$Message.loading({
        content: '提交中...',
        duration: 0
      });
      ApiRequest(apiurl + data, 'post').then((res) => {
        setTimeout(msg, 0);
        if (res.retStatus == '1') {
          this.$Message.success('提交成功');
        }
      });
    },

    // 保存
    handleSubmit (isCommit) {
      // 根据是否有单据号改变接口
      let apiurl = '';
      if (this.isNew == '1') {
        apiurl = '/sysback/productinfoupdate/createProductPicInfo';
      } else {
        apiurl = '/sysback/productinfoupdate/updateProductPicInfo';
      }
      let descript = '';
      let appdescript = '';
      let detailContent = this.pcDetail == '<p><br></p>' ? '' : this.pcDetail;
      if (this.animal == '1') {
        descript = detailContent;
        appdescript = detailContent;
      } else {
        descript = detailContent;
        appdescript = this.phoneDetail;
      }
      // 处理 商品主图 数据
      let mainimg = '';
      let mainimgtruing = '';
      let supplyvideo = '';
      let sellvideo = '';
      /* fmd-2021-10-06-需求校验变更 */
      /* if (
        this.goodsAvaterTruing.length === 0 &&
        this.goodsAvaterUntruing.length === 0
      ) {
        return this.$Message.warning('请上传商品主图');
      }
      if (
        this.goodsMultiangleTruing.length === 0 &&
        this.goodsMultiangleUntruing.length === 0
      ) {
        return this.$Message.warning('请上传多角度图');
      } */
      // 修改上传图片前缀问题 商品主图片（未精修）
      if (this.button1 == '本地上传' && this.goodsAvaterUntruing.length > 0) {
        mainimg = this.goodsAvaterUntruing[0].url;
      }
      if (this.button1 == '图片库上传' && this.goodsAvaterUntruing.length > 0) {
        mainimg = this.goodsAvaterUntruing[0].imageKey;
      }

      // 修改上传图片前缀问题 商品主图片（精修）
      if (this.button2 == '本地上传' && this.goodsAvaterTruing.length > 0) {
        mainimgtruing = this.goodsAvaterTruing[0].url;
      }
      if (this.button2 == '图片库上传' && this.goodsAvaterTruing.length > 0) {
        mainimgtruing = this.goodsAvaterTruing[0].imageKey;
      }
      /*	mainimg = this.goodsAvaterUntruing.length !== 0 ? this.goodsAvaterUntruing[0].imageKey : '';
        mainimgtruing = this.goodsAvaterTruing.length !== 0 ? this.goodsAvaterTruing[0].imageKey : ''; */
      supplyvideo = '';
      sellvideo = '';
      // 修改上传图片前缀问题 商品多角度 数据
      let multiList = [];
      if (this.goodsMultiangleTruing.length != 0) {
        let imageList = this.goodsMultiangleTruing;
        imageList.forEach(function (item, index) {
          let multiItem = {};
          if (item.imageKey) {
            multiItem = {
              basicImageKey: item.imageKey,
              position: '1' + index,
              trimming: '1'
            };
          } else {
            multiItem = {
              basicImageKey: item.url,
              position: '1' + index,
              trimming: '1'
            };
          }
          multiList.push(multiItem);
        });
      }
      //  修改上传图片前缀问题 商品多角度图（未精修）
      if (this.goodsMultiangleUntruing != 0) {
        let imageList = this.goodsMultiangleUntruing;
        imageList.forEach(function (item, index) {
          let multiItem = {};
          if (item.imageKey) {
            multiItem = {
              basicImageKey: item.imageKey,
              position: '2' + index,
              trimming: '2'
            };
          } else {
            multiItem = {
              basicImageKey: item.url,
              position: '2' + index,
              trimming: '2'
            };
          }
          multiList.push(multiItem);
        });
      }
      // 处理 SKU图片 数据
      let skulist = [];
      this.tableSelect.forEach(function (item, index) {
        let imageList = item.img;
        imageList.forEach(function (it, ix) {
          let obj = {};
          if (it.imageKey) {
            obj = {
              skuNo: item.skuNo,
              basicImageKey: it.imageKey,
              position: index + ix
            };
          } else {
            obj = {
              skuNo: item.skuNo,
              basicImageKey: it.url,
              position: index + ix
            };
          }
          skulist.push(obj);
        });
      });
      let data = {
        isCommit,
        productUuid: this.productUuid,
        recordNo: this.recordNo,
        type: this.isNew,
        descriptionUpdate: {
          description: descript,
          appdescrition: appdescript,
          currency: this.animal
        },
        mainImageUpdate: {
          mainImageKey: mainimg,
          videoKey: supplyvideo,
          saleVideoKey: sellvideo,
          trimmingKey: mainimgtruing
        },
        multiImageUpdateList: multiList,
        skuImageUpdateList: skulist
      };
      this.saveBtnLoading = true;
      ApiRequest(apiurl, 'post', data).then((res) => {
        this.saveBtnLoading = false;
        if (res.retStatus == '1') {
          this.$Message.success('操作成功');
        }
      }).catch(() => {
        this.saveBtnLoading = false;
      });
    }
  }
};
</script>

<style lang="less" scoped>
.content-wrap {
  background-color: #fff;
  padding: 10px;
  .head {
    margin: 10px 0;
    .title {
      font-size: 16px;
      font-weight: 500;
    }
    a {
      float: right;
      margin-left: 10px;
    }
  }
}
.note {
  font-size: 12px;
  color: orange;
}

.card-title {
  font-size: 16px;
  color: #17233d;
  font-weight: 500;
  height: 50px;
  line-height: 50px;
  margin-top: -16px;
  border-bottom: 1px solid #e8eaec;
}
.mr-10 {
  margin-right: 10px;
}
.item-wrap {
  padding: 10px;
  border: 1px dashed #ccc;
}
.sku-info {
  height: 162px;
  width: 300px;
  padding: 5px;
  float: left;
  // border: 1px dashed #ccc;
  margin-right: 10px;
}
.sku-img {
  float: left;
}
</style>
